package com.test.burnincash.aaahpoppomelo.bean;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.test.burnincash.aaahpoppomelo.util.http_hpoppomelo.HttpManager_hpoppomelo;
import com.test.burnincash.util_burnin.StringUtil_burnin;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Comparator;

public class UserData_hpoppomelo {

    private ArrayList<Order_hpoppomelo> orders = new ArrayList<>();
    private ArrayList<String> customers = new ArrayList<>();

    private static class Inner{
        private static UserData_hpoppomelo instance = new UserData_hpoppomelo();
    }

    private UserData_hpoppomelo(){}

    public static UserData_hpoppomelo getInstance(){
        return Inner.instance;
    }

    public static void parse(String jsonStr){
        Inner.instance.clear();
        try {
            JSONObject jsonObject = new JSONObject(jsonStr);
            JSONArray jsonArray = jsonObject.optJSONArray("orders");
            for (int i=0;i<jsonArray.length();i++){
                Inner.instance.addOrder(new Gson().fromJson(jsonArray.optJSONObject(i).toString(),Order_hpoppomelo.class));
            }

            Object customerObj = jsonObject.opt("customers");
            if (customerObj instanceof JSONArray){
                JSONArray customerJa = (JSONArray) customerObj;
                for (int i=0;i<customerJa.length();i++){
                    Inner.instance.addCustomer(customerJa.getString(i));
                }
            }
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }

    }

    public ArrayList<Order_hpoppomelo> getOrders() {
        if (orders==null) return new ArrayList<>();
        orders.sort(Comparator.comparingInt(Order_hpoppomelo::getOrderNumber));
        return orders;
    }

    public ArrayList<String> getCustomers() {
        if (customers==null) return new ArrayList<>();
        return customers;
    }

    public void addOrder(Order_hpoppomelo order){
        orders.add(order);
    }

    public void addCustomer(String customer){
        customers.add(StringUtil_burnin.getSafeString(customer));
    }

    public boolean containOrderNum(int orderNum){
        for (Order_hpoppomelo order:orders){
            if (order.getOrderNumber()==orderNum) return true;
        }
        return false;
    }

    public void uploadData(){

        JsonObject jsonObject = new JsonObject();

        JsonArray ordersJsonArray = new JsonArray();
        for (Order_hpoppomelo order:orders){
            ordersJsonArray.add(order.toJson());
        }
        jsonObject.add("orders",ordersJsonArray);

        jsonObject.add("customers",new Gson().toJsonTree(customers));

        HttpManager_hpoppomelo.getInstance().saveData(jsonObject.toString());

    }

    public void clear(){
        orders.clear();
        customers.clear();
    }

}
